package com.mnnu.controller;

import com.mnnu.pojo.Emp;
import com.mnnu.pojo.Result;
import com.mnnu.service.EmpService;
import com.mnnu.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class LoginController {

    @Autowired
    private EmpService empService;
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 登录校验
     * @param emp
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Emp emp) {
        log.info("登录请求");
        // 查询用户是否存在
        Emp res = empService.queryByInfos(emp);

        if (res != null) {
            // 用户存在，生成jwt令牌返回
            Map claims = new HashMap<String, Object>();
            claims.put("id", res.getId());
            claims.put("username", emp.getUsername());
            claims.put("password", emp.getPassword());
            String jwt = jwtUtils.generateJwt(claims);
            return Result.success((Object) jwt);
        }
        // 用户不存在，返回错误信息
        return Result.error("当前用户不存在！");
    }
}
